<?

//Initiate Authenticate
SecurityRedirect ();

//initiate Vars
define("PRIMARY_KEY","nobkt");
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");
//$FileName       = "ais_transaction_memotrans.php";
$FileName        =  GetScriptName();
$FileName       = "ais_transaction_ap_oth.php";
$FileTemplate   = "ais_transaction_ap_oth_form.html";
$SubHeaderTitle = "Transaction Account Payable - New Account Payable Entry";
$TableName      = "ais_memorial";
$HTMLFormName   = "MemorialTransForm";
$MaxGrid        = "100";
$KTRASL         = GetOfficeID();
//$HTMLFormName2  = "BudgetForm";
$FormName   = "MemorialTransForm";
$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("uraian"=>"0","urut"=>"","skada"=>"","jumlah"=>"number","dk"=>"","noorder"=>"","debtur"=>"","kdact"=>"","debnam"=>"","memorial_id"=>"","tgltrm"=>"date","jo_code" => "");

//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name",1);
$FormCValue    = BuildHTMLField($FormFields,"value",1);


$rate    = StrToNumber (GetParam("rate",""));

list($FDay,$FMonth,$FYear) = explode("/",GetParam("tglbkt",""));
$tglbkt = "$FYear-$FMonth-$FDay";

list($FDay,$FMonth,$FYear) = explode("/",GetParam("tgltrm",""));
$tgltrm = "$FYear-$FMonth-$FDay";


//************ FORM ACTION **************
if (trim(GetParam("form",""))==trim($HTMLFormName)) {
    if (GetParam("FormAction","")=="Save") {
        

        if (trim(GetParam("nobkt",""))=="AUTO NUMBERED BY SYSTEM")  {
            $ObjNumber  = new autonumber(GetParam("tglbkt",""));
            $TransNo = $ObjNumber->GetNumber("AP");
            FormSave("ais_memorial", "jumlah", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"curr"=>GetParam("curr",""),"rate"=>$rate,"tglbkt"=>$tglbkt,"nobkt"=>$TransNo,"ktrasl"=>GetOfficeID(),"noref"=>GetParam("noref","")),"memorial_id");

            $DBConnection->add_data("ais_memorial","urut","999");
            $DBConnection->add_data("ais_memorial","ktrasl",GetOfficeID());
            $DBConnection->add_data("ais_memorial","kdbank",GetParam("kdbank",""));
            $DBConnection->add_data("ais_memorial","ledger",GetPeriod(GetParam("tglbkt","")));
            $DBConnection->add_data("ais_memorial","curr",GetParam("curr",""));
            $DBConnection->add_data("ais_memorial","rate",$rate);
            $DBConnection->add_data("ais_memorial","noref",GetParam("noref",""));
            $DBConnection->add_data("ais_memorial","nobkt",$TransNo);
            $DBConnection->add_data("ais_memorial","tglbkt",$tglbkt);
            $DBConnection->add_data("ais_memorial","dk",GetParam("dk999",""));
            $DBConnection->add_data("ais_memorial","noorder",GetParam("noorder999",""));
            $DBConnection->add_data("ais_memorial","debtur",GetParam("debtur999",""));
            $DBConnection->add_data("ais_memorial","debnam",GetParam("debnam999",""));
            $DBConnection->add_data("ais_memorial","skada",GetParam("skada999",""));
            //$DBConnection->add_data("ais_memorial","tgltrm999",$tgltrm999);
			

            $DBConnection->add_data("ais_memorial","tgltrm",$tglterm);
            $DBConnection->add_data("ais_memorial","uraian",GetParam("uraian999",""));
            $DBConnection->add_data("ais_memorial","kdact",GetParam("kdact999",""));
            $DBConnection->add_data("ais_memorial","jumlah",StrToNumber(GetParam("total_trans","")));
            $DBConnection->add_data("ais_memorial","rupiah",StrToNumber(GetParam("total_trans","")) * $rate);
            //$DBConnection->add_data("ais_memorial","noref",GetParam("noref999",""));
            $DBConnection->InsertGrid();
//          $DBConnection->dbc->query("UPDATE ais_memorial_history SET memo_jour='".$TransNo."', jml_memo='".StrToNumber(GetParam("total_trans",""))."' WHERE memoesti='".GetParam("aslref","")."' AND ktrasl='".GetOfficeID()."'");

            SetLogActivity($TransNo,"Create","");
        } else {
            $TransNo = GetParam("nobkt","");
            $DBConnection->dbc->query("DELETE FROM ais_memorial WHERE nobkt='".$TransNo."' AND ktrasl='".GetOfficeID()."'");
            $DBConnection->dbc->query("DELETE FROM ais_hutang WHERE nobkt='".$TransNo."' AND ktrasl='".GetOfficeID()."'");
            $DBConnection->dbc->query("DELETE FROM ais_piutang WHERE nobkt='".$TransNo."' AND ktrasl='".GetOfficeID()."'");

            FormSave("ais_memorial", "jumlah", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"curr"=>GetParam("curr",""),"rate"=>$rate,"tglbkt"=>$tglbkt,"nobkt"=>$TransNo,"ktrasl"=>GetOfficeID()),"memorial_id");

            $DBConnection->add_data("ais_memorial","urut","999");
            $DBConnection->add_data("ais_memorial","ktrasl",GetOfficeID());
            $DBConnection->add_data("ais_memorial","kdbank",GetParam("kdbank",""));
            $DBConnection->add_data("ais_memorial","ledger",GetPeriod(GetParam("tglbkt","")));
            $DBConnection->add_data("ais_memorial","curr",GetParam("curr",""));
            $DBConnection->add_data("ais_memorial","rate",$rate);
            $DBConnection->add_data("ais_memorial","noref",GetParam("noref",""));
            $DBConnection->add_data("ais_memorial","nobkt",$TransNo);
            $DBConnection->add_data("ais_memorial","tglbkt",$tglbkt);
            $DBConnection->add_data("ais_memorial","dk",GetParam("dk999",""));
            $DBConnection->add_data("ais_memorial","noorder",GetParam("noorder999",""));
            $DBConnection->add_data("ais_memorial","debtur",GetParam("debtur999",""));
            $DBConnection->add_data("ais_memorial","debnam",GetParam("debnam999",""));
            $DBConnection->add_data("ais_memorial","skada",GetParam("skada999",""));
            //$DBConnection->add_data("ais_memorial","tgltrm999",$tgltrm999);
        
            $DBConnection->add_data("ais_memorial","tgltrm",$tgltrm);

            $DBConnection->add_data("ais_memorial","uraian",GetParam("uraian999",""));
            $DBConnection->add_data("ais_memorial","kdact",GetParam("kdact999",""));
            $DBConnection->add_data("ais_memorial","jumlah",StrToNumber(GetParam("total_trans","")));
            $DBConnection->add_data("ais_memorial","rupiah",StrToNumber(GetParam("total_trans","")) * $rate);
            //$DBConnection->add_data("ais_memorial","noref",GetParam("noref999",""));
            $DBConnection->InsertGrid();

//          $DBConnection->dbc->query("UPDATE ais_memorial_history SET memo_jour='".$TransNo."', jml_memo='".StrToNumber(GetParam("total_trans",""))."' WHERE memoesti='".GetParam("aslref","")."' AND ktrasl='".GetOfficeID()."'");

            SetLogActivity($TransNo,"Update","");
            }

        $SQL = "INSERT INTO ais_hutang (ledger,ktrasl,tglbkt,nobkt,urut,noref,nobkta,skada,debtur,debnam,uraian,curr,jumlah,dk,rate,rupiah,srt,jo_code)
                SELECT ledger,ktrasl,tglbkt,nobkt,urut,noref,noref,skada,debtur,debnam,uraian,curr,jumlah,dk,rate,rupiah,if(dk='D','2','1'),jo_code FROM ais_memorial WHERE (skada like '3%' OR skada like '4%') AND nobkt='".$TransNo."' ";
        $DBConnection->dbc->query($SQL);
        //$DBConnection->dbc->debug();

        $SQL = "INSERT INTO ais_piutang (ledger,ktrasl,tglbkt,nobkt,normut,noref,nobkta,skada,debtur,debnam,uraian,curr,jumlah,dk,rate,rupiah,srt,jo_code)
                SELECT ledger,ktrasl,tglbkt,nobkt,urut,noref,noref,skada,debtur,debnam,uraian,curr,jumlah,dk,rate,rupiah,if(dk='D','1','2'),jo_code FROM ais_memorial WHERE (skada like '0006%' OR skada like '0007%') AND nobkt='".$TransNo."' ";
        $DBConnection->dbc->query($SQL);

        $DBConnection->dbc->query("UPDATE ais_memorial SET app1='".GetParam("app1","")."',nmapp1='".GetParam("nmapp1","")."' WHERE nobkt='$TransNo'");
        header("Location: $FileName?PageMode=Form&nobkt=$TransNo");
                exit;
    }
    if (GetParam("FormAction","")=="Delete") {
//      print "Deleted"."<br>\n";
        $SQL = "DELETE FROM  ais_memorial WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        $SQL = "DELETE FROM  ais_piutang WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        $SQL = "DELETE FROM  ais_hutang WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        SetLogActivity($TransNo,"Delete","");
        header("Location: $FileName?PageMode=Form");
        exit;
    }
}

//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
$VerifyFields = array();
//$SessionVar    = "Stuck";

/*
$VerifyFields = array(      "nobkt"=>"ID No.",
                            "tglbkt"=>"Transaction Date",
                            "curr"=>"Currency",
                            "debtur"=>"Debnam",
                            "uraian1"=>"Uraian On Line 1",
                            "uraian999"=>"Uraian On Line 999",
                            "skada999"=>"COA On Line 999",
                            "noref999"=>"Ref On Line 999");

*/

VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar);

//modified by dyah. 27 july 2009
$PERIOD_OPENED = 1;
if (GetParam(PRIMARY_KEY,"")) {
    $SQLCount     = "SELECT count(*) FROM `$TableName`";
    $SQLCount    .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."' AND urut<>999";
    $Count        = $DBConnection->dbc->get_var($SQLCount);

    $CheckPeriodQuery = "SELECT tglbkt FROM `$TableName`";
    $CheckPeriodQuery .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."'";
    $TglTrans = $DBConnection->dbc->get_var($CheckPeriodQuery);
    $PERIOD_OPENED = CheckPeriod($TglTrans);
} else $Count=0;

//$NewDataStart = $Count + 1;
$NewDataStart = 1;
$InitFunction = "Masking();Masking2();";

//$VerifyGrids = array("uraian"=>"0","jumlah"=>"number","skada"=>"0","dk"=>"","debtur"=>"","noref"=>"");
//$VerifyGrids = array("uraian"=>"0","jumlah"=>"number","skada"=>"0","dk"=>"","debtur"=>"");
$VerifyGrids = array();
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array("tglbkt"=>"date","rate"=>"number"),"2");
$JSMasks  = $Masking1.$Masking2;

Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);

//************ SET FORM MODE ***************
if (GetParam(PRIMARY_KEY,"")) {
  $FormMode = "Edit";
  if (!isApproved(GetParam("nobkt",""))) $USER_CANPRINT="";
  else $USER_CANPRINT="1";
} else {
  $FormMode = "Add";
  $USER_CANPRINT="";
}

//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQL      = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQL     .= " AND ktrasl='".GetOfficeID()."'";
    $SQLGrid  = $SQL." ORDER BY urut";
}

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************
//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Bank:
$SQLBank = "SELECT * FROM tblbank ORDER BY banknam";
//Select Activity
$SQLAct  = "SELECT  * FROM tblactivity ORDER BY kdact";



$HeaderFields = array("nobkt"=>"0","tglbkt"=>"date","curr"=>"","rate"=>"number","debtur"=>"","debnam"=>"","kdact"=>"","app1"=>"","nmapp1"=>"","noref"=>"");
//Leave Here Untouch
$FormHName     = BuildHTMLField($HeaderFields,"name",1);
$FormHValue    = BuildHTMLField($HeaderFields,"value",1);
$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= "WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$TBS->MergeBlock("deptblk",$DBMysql,$SQLDept);
$TBS->MergeBlock("actblk",$DBMysql,$SQLAct);
$TBS->MergeBlock("actblk999",$DBMysql,$SQLAct);
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);
$TBS->MergeBlock("receiptblk",$DBMysql,$SQLReceipt);


//Total 999 Values
/*
$Fields9       = array("noref999"=>"0","jumlah999"=>"number","skada999"=>"0","untush999"=>"0");
$Form9Value    = BuildHTMLField($Fields9,"value",1);
*/
if (GetParam(PRIMARY_KEY,""))
$SQL999 = "SELECT * FROM ais_memorial "."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."' ";
elseif (GetParam("trno",""))
$SQL999 = "SELECT * FROM ais_memorial "."WHERE ".PRIMARY_KEY." ='".GetParam("trno","")."' AND ktrasl='".GetOfficeID()."' ";

$SQL999 = $SQL999." AND urut = 999 ";

$TBS->MergeBlock("dept999blk",$DBMysql,$SQLDept);
if (GetParam(PRIMARY_KEY,"") || GetParam("trno","")) {$TBS->MergeBlock("blg9",$DBMysql,$SQL999);}
else $TBS->MergeBlock("blg9",$FormCValue);

// HTML Value

//echo $SQLHeader;
$TBS->MergeBlock("headbln",$FormHName);
if (GetParam(PRIMARY_KEY,"") || GetParam("trno","")) {$TBS->MergeBlock("headblv",$DBMysql,$SQLHeader);}
else $TBS->MergeBlock("headblv",$FormHValue);



//********************************* HTML GRID *********************************************
//HTML Grid
if (GetParam(PRIMARY_KEY,""))
$SQLGrid = "SELECT * FROM ais_memorial "."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."' AND urut<>999 ORDER BY urut";
elseif (GetParam("trno",""))
$SQLGrid = "SELECT * FROM ais_memorial "."WHERE ".PRIMARY_KEY." ='".GetParam("trno","")."' AND ktrasl='".GetOfficeID()."' AND urut<>999 ORDER BY urut";

//print $SQLGrid;
$Result  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

//$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

$TBS->MergeBlock("blg",$Result);
$TBS->Show();


//*************** ACTION FUNCTION *******************
function isApproved($nobkt) {
    global $DBConnection;
        $SQL = "SELECT app1 FROM ais_memorial WHERE nobkt='$nobkt'";
        return $DBConnection->dbc->get_var($SQL);
}

function FormInsert() {
    global $DBConnection,$FileName;
    $DBConnection->Insert();
    header("Location: $FileName?PageMode=Form");
    exit;
}

function FormUpdate() {
    global $DBConnection;
    $DBConnection->Update();
}

function FormDelete() {
    global $DBConnection,$FileName,$TableName;
    $DBConnection->deleteGrid("$TableName","nobkt");
    header("Location: $FileName");
    exit;
}

function FormSearch () {

}

function FormCancel () {
    global $FileName;
    header("Location: ".$FileName);
    exit;
}

function FormSaveHutang ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey) {
    global $FileName, $MaxGrid, $DBConnection;
    $TotalData = $MaxGrid * 2;
    $NewDataStart = GetParam("NewData","0");
    
//  $NewDataStart = 1;
    for ($a=1;$a<=$TotalData;$a++) {
        if (substr(GetParam($keyField.$a,""),0,1)=='3' || substr(GetParam($keyField.$a,""),0,1)=='4') {
            foreach ($FormFields as $key=>$formatting) {
                if (!GetParam($keyField.$a,"")) {
                    $EndOfData = 1;
                    break;
                }
                
                $value = GetParam($key.$a,"");
                
                if ($formatting=="number") $value = str_replace(",","",$value);
                if ($formatting=="date") {
                    list($day,$month,$year) = explode("/",$value);
                    $value = "$year-$month-$day";
                }
                
                if($key == "debtur")
                {
					$value_edit = GetParam("debtur","");
					$DBConnection->add_data($table,$key,$value_edit);
				}
				
				else if($key == "debnam")
				{
					$value_edit = GetParam("debnam","");
					$DBConnection->add_data($table,$key,$value_edit);
				}
                
                else
                {
                   $DBConnection->add_data($table,$key,$value);
			    }

                                
            }
            $rate = StrToNumber(GetParam("rate",""));
            $jmh  = StrToNumber(GetParam("jumlah".$a,""));
            $rupiah = $rate * $jmh;
            $DBConnection->add_data($table,"rupiah",$rupiah);
            if ($EndOfData) {
                break;
            }
            if (strlen($SpecialCase)) {
                foreach ($SpecialCase as $key => $value) {
                //  print "add_data($table,$key,$value);<br>";
                    $DBConnection->add_data($table,$key,$value);
                }
            }
    //      print "$a < $NewDataStart<br>";
            if ($a < $NewDataStart) {
                 if (strlen($PrimaryKey)) {
                    $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
                 } else {
                    $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
                 }
            } else {
                $DBConnection->InsertGrid();
            }
            }
    }
    $DBConnection->clearData();
}


function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey) {
    global $FileName, $MaxGrid, $DBConnection;
    $TotalData = $MaxGrid * 2;
    $NewDataStart = GetParam("NewData","0");
//  $NewDataStart = 1;
   
    for ($a=1;$a<=$TotalData;$a++) {
		
		 if (!GetParam("txtCheck".$a,"")) {
			 
				foreach ($FormFields as $key=>$formatting) 
				{
					if (!GetParam($keyField.$a,"")) 
					{
						$EndOfData = 1;
						break;
					}
					
					$value = GetParam($key.$a,"");
					if ($formatting=="number") $value = str_replace(",","",$value);
					
					if ($formatting=="date") 
					{
						list($day,$month,$year) = explode("/",$value);
						$value = "$year-$month-$day";
					}
					
					if($key == "debtur")
					{
						$value_edit = GetParam("debtur","");
						$DBConnection->add_data($table,$key,$value_edit);
					}
					
					else if($key == "debnam")
					{
						$value_edit = GetParam("debnam","");
						$DBConnection->add_data($table,$key,$value_edit);
					}
					
					else
					{
					   $DBConnection->add_data($table,$key,$value);
					}
					
					
				}
				
				$rate = StrToNumber(GetParam("rate",""));
				$jmh  = StrToNumber(GetParam("jumlah".$a,""));
				$rupiah = $rate * $jmh;
				$DBConnection->add_data($table,"rupiah",$rupiah);
				
				if ($EndOfData) 
				{
					break;
				}
				
				if (strlen($SpecialCase)) 
				{
					foreach ($SpecialCase as $key => $value) {
					//  print "add_data($table,$key,$value);<br>";
						$DBConnection->add_data($table,$key,$value);
					}
				}
				
		//      print "$a < $NewDataStart<br>";
				if ($a < $NewDataStart) 
				{
					 if (strlen($PrimaryKey)) {
						$DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
					 } else {
						$DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
					 }
				} 
				
				else 
				{
					$DBConnection->InsertGrid();
				}
				
				
           }
           
    }
    
    $DBConnection->clearData();
}
//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield) {
        global $DBConnection;
        for ($x=0;$x<count($arrayfield);$x++) {
            $DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
        }
}

function DeleteRecord ($sequence_name,$PageSize) {
    global $DBConnection,$FileName,$TableName;
    for ($x=1;$x<=$PageSize;$x++) {
        if (GetParam($sequence_name.$x,"")) {
            $DBConnection->deleteGrid("$TableName","memorial_id",$sequence_name.$x);
        }
    }
}

function BuildFields ($FormFields) {
        global $DBConnection;
        $str = "";
        foreach ($FormFields as $key=>$formatting) {
            if (strlen($str)) $str .= ",$key";
            else $str = "$key";
        }
        return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
        global $DBConnection;
        $array_fields = array();
        for ($x=0;$x<$MaxGrid;$x++) {
            foreach ($FormFields as $key=>$formatting){
                $a=$x+1;
                $array_fields[$key.$a] = "$formatting";
            }
        }
        return $array_fields;
}
?>
